package co.fitstart.admin.web.controller.user.satisfaction;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.BusinessException;
import com.demo2do.core.support.Result;
import com.demo2do.core.utils.JsonUtils;

import co.fitstart.admin.entity.security.Login;
import co.fitstart.admin.service.CouponService;
import co.fitstart.admin.service.PrincipalService;
import co.fitstart.admin.service.SatisfactionSurveyService;
import co.fitstart.admin.service.SiteService;
import co.fitstart.admin.web.interceptor.MenuSetting;
import co.fitstart.admin.web.resolver.Secure;
import co.fitstart.admin.web.view.ExcelTemplateView;
import co.fitstart.entity.coupon.Coupon;
import co.fitstart.entity.market.satisfaction.SatisfactionSurvey;
import co.fitstart.entity.principal.Principal;
import co.fitstart.entity.site.Site;

/**
 * 礼品券核销
 * @author Administrator
 *
 */
@Controller
@RequestMapping("gift-coupons")
@MenuSetting("menu-user")
public class GiftCouponController {

    private static final Logger logger = LoggerFactory.getLogger(GiftCouponController.class);

    @Autowired
    private SiteService siteService;

    @Autowired
    private PrincipalService principalService;

    @Autowired
    private CouponService<Coupon> couponService;

    @Autowired
    private SatisfactionSurveyService satisfactionSurveyService;

    /**
     * 
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    @MenuSetting("submenu-gift-coupon-management")
    public ModelAndView list() {
        ModelAndView modelAndView = new ModelAndView("market/satisfaction-survey/gift-coupon");
        
        return modelAndView;
    }

    /**
     * 
     * @param code
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.GET)
    @MenuSetting("submenu-gift-coupon-management")
    public ModelAndView list(@RequestParam("code") String code) {
        ModelAndView modelAndView = new ModelAndView("market/satisfaction-survey/gift-coupon");
        
        List<SatisfactionSurvey> surveys = satisfactionSurveyService.list(code);
        
        modelAndView.addObject("surveys", surveys);
        modelAndView.addObject("search", true);
        modelAndView.addObject("code", code);
        
        return modelAndView;
    }

    /**
     * 
     * @param couponId
     * @return
     */
    @RequestMapping(value = "/{couponId}/use", method = RequestMethod.GET)
    @MenuSetting("submenu-gift-coupon-management")
    public ModelAndView use(@PathVariable("couponId") Long couponId) {
        ModelAndView modelAndView = new ModelAndView("market/satisfaction-survey/gift-coupon-use");
        
        modelAndView.addObject("couponId", couponId);
        
        return modelAndView;
    }

    /**
     * 
     * @param couponId
     * @return
     */
    @RequestMapping( value = "/{couponId}/use", method = RequestMethod.PATCH)
    public @ResponseBody String onUse(@PathVariable("couponId") Long couponId,
                                      @RequestParam("gift") String gift) {
        
        Result result = new Result();
        
        try {
            Coupon coupon = couponService.load(Coupon.class, couponId);
            
            couponService.useGiftCoupon(coupon, gift);
            
            result.success().message("优惠券核销成功！");
        } catch(BusinessException e) {
            result.fail().message(e.getMessage());
        } catch(Exception e) {
            logger.error("use error", e);
            
            result.fail().message("优惠券核销失败！");
            
        }
        
        return JsonUtils.toJsonString(result);
    }

    /**
     * 
     * @return
     */
    @RequestMapping(value = "/export-view", method = RequestMethod.GET)
    @MenuSetting("submenu-gift-coupon-management")
    public ModelAndView export() {
        ModelAndView modelAndView = new ModelAndView("market/satisfaction-survey/gift-coupon-export");
        
        modelAndView.addObject("today", DateFormatUtils.format(new Date(), "yyyy-MM-dd"));
        
        return modelAndView;
    }

    /**
     * 
     * @param login
     * @param siteId
     * @param beginDate
     * @param endDate
     * @return
     */
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public ModelAndView onExport(@Secure Login login,
                                 @RequestParam(value = "siteId", required=false) Long siteId,
                                 @RequestParam(value = "beginDate") @DateTimeFormat(pattern = "yyyy-MM-dd") Date beginDate,
                                 @RequestParam(value = "endDate") @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate) {
        ModelAndView modelAndView = new ModelAndView(new ExcelTemplateView("gift-coupon-report.xls"));
        
        List<SatisfactionSurvey> surveys = new ArrayList<>();
        
        Site site = null;
        if(siteId != null) {
            site = siteService.load(siteId);
        }
        
        if(login.isRoot() || login.isAdmin()) {
            if(beginDate == null || endDate == null) {
                beginDate = new Date();
                endDate = new Date();
            }
            
            surveys = satisfactionSurveyService.listUsedGiftCoupon(site, beginDate, endDate);
        } else if(login.isAreaManager() || login.isAreaServer()) {
            Principal principal = principalService.load(Principal.class, login.getId());
            List<Site> sites = siteService.listSite(principal);
            
            if(!sites.isEmpty()) {
                if(site == null) {
                    surveys = satisfactionSurveyService.listUsedGiftCoupon(sites, beginDate, endDate);
                } else if(sites.contains(site)) {
                    surveys = satisfactionSurveyService.listUsedGiftCoupon(site, beginDate, endDate);
                }
            }
        } else if(login.isSiteManager() || login.isSiteServer()) {
            surveys = satisfactionSurveyService.listUsedGiftCoupon(login.getSite(), beginDate, endDate);
        }
        
        modelAndView.addObject("surveys", surveys);
        modelAndView.addObject("beginDate", DateFormatUtils.format(beginDate, "yyyy-MM-dd"));
        modelAndView.addObject("endDate", DateFormatUtils.format(endDate, "yyyy-MM-dd"));
        
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        modelAndView.addObject("fmt", fmt);
        
        return modelAndView;
    }
}
